package us.codecraft.webmagic.model;

import java.net.MalformedURLException;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.model.annotation.ExtractBy;
import us.codecraft.webmagic.model.annotation.TargetUrl;
import us.codecraft.webmagic.selector.Type;

@TargetUrl("http://api.mayiyiyi.com/v1/cate/catecon*")
@ExtractBy(value = "router('def process(obj){\nreturn us.codecraft.webmagic.model.AntStore.decrypt(obj);\n}').json('$..list[*]')", multi = true, source = Source.RawText)
public class AntItems implements AfterExtractor {

    @ExtractBy(value = "router('def process(obj){\nreturn us.codecraft.webmagic.model.AntStore.decrypt(obj);\n}').json('$..pageNum')", source = Source.RawText)
    private Integer pageNum;

    @ExtractBy(value = "router('def process(obj){\nreturn us.codecraft.webmagic.model.AntStore.UrlHandle(obj,false,'UTF-8');\n}').regex('cid=([^&]+)')", source = Source.Url, type = Type.mixe)
    private String cid;

    @ExtractBy(value = "$..id", type = Type.json, notNull = true)
    private String id;

    @ExtractBy(value = "$..pic", type = Type.json)
    private String pic;

    @Override
    public void afterProcess(Page page) {
        Boolean flag = (Boolean) page.getRequest().getExtra("flag");
        if (flag != null && flag == true) {
            page.getRequest().putExtra("flag", false);
            for (int i = 2; i <= pageNum; i++) {
                try {
                    Request req = new Request(AntStore.getCatecon(this.cid, i + ""));
                    req.putExtra("name", page.getRequest().getExtra("name"));
                    page.addTargetRequest(req);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            Request req = new Request(AntStore.getDetail(this.id));
            req.putExtra("name", page.getRequest().getExtra("name"));
            req.putExtra("id", this.cid);
            req.putExtra("pic", this.pic);
            page.addTargetRequest(req);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

}
